<?php
namespace app\admin\model;
use think\Loader;
use think\Model;
use think\Validate;

class Login extends Model
{
    protected $pk = 'id';//主键
    //设置当前模型对应的完整数据表名称
    protected $table = 'fly_user';

    /**
     * 登录
     * $data 是接收的post数据
     */
    public function login($data)
    {
        //1.执行验证
       $validate = new Validate([
            'name'=>'require',
            'pwd'=>'require'
        ],[
           'name.require'=>'请输入管理账号',
           'pwd.require'=>'请输入密码'
            ]
    );
//        //如果验证不通过
        if (!$validate->check($data)) {
            return ['valid' => 0, 'msg' => $validate->getError()];
        }
        //2.比对用户名和密码是否正确
        $userInfo = $this->where('name', $data['name'])->where('pwd', md5($data['pwd']))->where('sort', 1)->find();
        // dump($userInfo);die;
        if (!$userInfo) {
            //说明在数据库未匹配到相关数据
            return ['valid' => 0, 'msg' => '用户名或者密码不正确 或没有权限'];
        }
        //3.将用户信息存入到session中

        $admin  = array('id' => $userInfo['id'],'name'=>$userInfo['name'] );
        session('admin', $admin);
        return ['valid' => 1, 'msg' => '登录成功'];
    }
    /**
     * 修改密码
     * $data 是接收的post数据
     */
    public function pwd($data){
        //执行验证
        $validate = new Validate([
            'pwd'  => 'require',
            'new_pwd' => 'require',
            'confirm_pwd' => 'require|confirm:new_pwd'
        ],[
            'pwd.require'  => '请输入原始密码',
            'new_pwd.require' => '请输入新密码',
            'confirm_pwd.require' => '请重复新密码',
            'confirm_pwd.confirm' => '确认密码与新密码不一致'

            ]
    );
        if (!$validate->check($data)) {
            return ['valid'=> 0,'msg'=>$validate->getError()];
        }
        //原始密码是否正确
        $userInfo = $this->where('pwd',md5($data['pwd']))->where('id',session('admin.id'))->find();
        if(!$userInfo){
            return ['valid'=>0, 'msg'=>'原始密码不正确'];
        }
        //修改密码
        // save方法第二个参数为更新条件
        $res = $this->save([
            'pwd'  =>md5($data['new_pwd']),
        ],[$this->pk => session('admin.id')]);
        if($res){
            return ['valid'=>1, 'msg'=>'密码修改成功'];
        }else{
            return ['valid'=>0, 'msg'=>'密码修改失败'];

        }

    }
}